package base.client;


import base.model.NettyMessage;
import base.model.NettyMessageDecoder;
import base.model.NettyMessageEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 客户端代码
 * Created by wuhui on 2016/8/4.
 */
@Slf4j
public class NettyClient {
    private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    EventLoopGroup group = new NioEventLoopGroup();
    public static void main(String[] args) throws Exception {
        new NettyClient().connect(80,"172.16.100.224");
    }
    public void connect(final int port, final String host) throws  Exception{
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY,true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel channel) throws Exception {
                channel.pipeline().addLast(new NettyMessageDecoder(1024*1024,4,4,-8,0));
                channel.pipeline().addLast("MessageEncoder",new NettyMessageEncoder());
                channel.pipeline().addLast("readTimeout",new ReadTimeoutHandler(50));
              //channel.pipeline().addLast("loginAuth",new LoginAuthReqHandler());
           //   channel.pipeline().addLast("heartBeat",new HeartBeatReqHandler());
            }
        });
        ChannelFuture channelFuture = b.connect(new InetSocketAddress(host,port),new InetSocketAddress("172.16.100.224",22514)).sync();
      //  channelFuture.channel().closeFuture().sync();
        Channel channel =channelFuture.channel();
//        for (int i = 0; i <1 ; i++) {
            channel.writeAndFlush(NettyMessage.newNettyMessage((byte)127));
//        }
//        while (true){
//            channel.writeAndFlush(NettyMessage.newNettyMessage((byte)127));
//            channel.flush();
//        }
//        executorService.execute(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    TimeUnit.SECONDS.sleep(5);
//                    connect(80,"127.0.0.1");
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });
    }
}
